package com.basic.library.base

import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.basic.library.brvah.MBaseViewHolder
import com.chad.library.adapter.base.BaseQuickAdapter


/**
 * 解决 getChildAsT 在java中无法调用的问题
 */
abstract class BaseActivityKt<V : ViewDataBinding, VM : BaseViewModel> : BaseActivity<V, VM>() {
    private var swipe: SwipeRefreshLayout? = null
    private var recycler: RecyclerView? = null
    var hasInitSwipe = false //检查是否有SwipeRefreshLayout的标志， 不需要检查时，初始化置true就行
    private var recyclerAdapter: BaseQuickAdapter<Any, MBaseViewHolder>? = null

    /**
     *  改写对 SwipeRefreshLayout 动画的操作
     *  hasInitSwipe是全局刷新的开关
     *  有SwipeRefreshLayout布局时，默认用SwipeRefreshLayout的刷新动画，没有时用‘等待动画’
     */
    override fun loading(tag: String?) {
        if (tag != useDefaultLoadingView) {
            if (!hasInitSwipe) {
                swipe = getChildAsT<SwipeRefreshLayout>(activity.window.decorView)
                swipe?.run {
                    recycler = getChildAsT<RecyclerView>(this)
                    recycler?.run {
                        recyclerAdapter = adapter as BaseQuickAdapter<Any, MBaseViewHolder>?
                    }
                }
                hasInitSwipe = true
            }
            swipe?.run {
                // 第一页启动下拉刷新动画 (BaseQuickAdapter过滤感觉没必要)
//                if ((recyclerAdapter is MyBaseQuickAdapter
//                                && (recyclerAdapter as MyBaseQuickAdapter<Any, MBaseViewHolder>).page == 1)
//                        || (recyclerAdapter is MyBaseMultiItemQuickAdapter
//                                && (recyclerAdapter as MyBaseMultiItemQuickAdapter<MultiItemEntity, MBaseViewHolder>).page == 1))
                isRefreshing = true
            }
        }
        //没找到SwipeRefreshLayout 就用默认的等待框
        if (swipe == null || tag == useDefaultLoadingView)
            super.loading(tag)
    }


    /**
     *  这里就不写了，在MyBaseQuickAdapter中chargeRefresh，完美的解决了动画消失的操作
     */
    override fun dismiss(tag: String?) {
        super.dismiss(tag)
        swipe?.run {
            isRefreshing = false
        }
    }

}
